package com.yunc.modules.shop.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSpliter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.base.aspect.DataSource;
import com.yunc.base.aspect.DataSourceType;
import com.yunc.base.utils.R;
import com.yunc.base.utils.SecurityUtils;
import com.yunc.modules.shop.entity.Shop;
import com.yunc.modules.shop.service.IShopService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("shop")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShopController {

    private final IShopService shopService;

    @GetMapping("/page")
    public R page(Page<Shop> page, Shop shop){
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        shopService.page(page, qw);
        return R.ok().put("data", page.getRecords()).put("count", page.getTotal());
    }

    @GetMapping("/info")
    public R info(){
        // 根据登录用户获取
        String userId = SecurityUtils.getUserId();
        Shop shop = shopService.getByUserId(userId);
        return R.ok().put("shop", shop);
    }

    @GetMapping("/info/{id}")
    public R infoById(@PathVariable String id){
        Shop shop = shopService.getById(id);
        return R.ok().put("shop", shop);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @CacheEvict(value = {"shop-user"}, allEntries = true)
    public R save(Shop shop){
        shop.setCreateTime(new Date());
        boolean flag = shopService.save(shop);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @PutMapping(value = "/update")
    @CacheEvict(value = {"shop-user"}, allEntries = true)
    public R update(Shop shop){
        boolean flag = shopService.updateById(shop);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    @DeleteMapping("/delete/{ids}")
    @DataSource(value = DataSourceType.SHOP)
    @CacheEvict(value = {"shop-user"}, allEntries = true)
    public R delete(@PathVariable String ids){
        List<String> idsList = StrSpliter.splitTrim(ids, ',', true);
        if (CollUtil.isEmpty(idsList)) {
            return R.error("传入值格式错误");
        }
        boolean flag = shopService.removeByIds(idsList);
        if (flag) {
            return R.ok("删除成功");
        }
        return R.error("删除失败");
    }
}
